import type { Directive } from 'vue'

enum Direction {
  UP = 'up',
  DOWN = 'down',
  LEFT = 'left',
  RIGHT = 'right'
}

export const mouseDirection: Directive = {
  mounted(el: HTMLElement) {
    const { width, height } = el.getBoundingClientRect()
    const theta = Math.atan2(height, width)
    el.addEventListener('mouseenter', (e) => {
      const x = e.offsetX - width / 2,
        y = height / 2 - e.offsetY
      const angle = Math.atan2(y, x)
      let dirc: Direction = Direction.UP
      if (angle < theta && angle > -theta) {
        dirc = Direction.RIGHT
      } else if (angle < -theta && angle > -Math.PI + theta) {
        dirc = Direction.DOWN
      } else if (angle < Math.PI - theta && angle > -Math.PI + theta) {
        dirc = Direction.UP
      } else {
        dirc = Direction.LEFT
      }

      el.setAttribute('data-mouse-direction', dirc)
    })
  },
  unmounted(el: HTMLElement) {
    el.removeEventListener('mouseenter', () => {
      el.removeAttribute('data-mouse-direction')
    })
  }
}
